package com.shoponline.util;

import java.net.URL;

import javax.servlet.ServletException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernatePlugINForStruts implements PlugIn{

	public Configuration config;
	private SessionFactory factory;
	private String path = "/hibernate.cfg.xml";
	private static Class clazz = HibernatePlugINForStruts.class;
	public static final String KEY_NAME=clazz.getName();
	private Log log = LogFactory.getLog(clazz);
	
	
	public void setPath(String path){
		
		this.path = path;
		
	}
	
	@Override
	public void destroy() {
		
		try{
			
			factory.close();
			
		}catch(Exception e){
			
			log.error("unable to close factory",e);
			
		}
		
	}

	@Override
	public void init(ActionServlet servlet, ModuleConfig modConfig)
			throws ServletException {
		
		try{
			
			URL url = HibernatePlugINForStruts.class.getResource(path);
			config = new Configuration().configure(url);
			factory = config.buildSessionFactory();
			servlet.getServletContext().setAttribute(KEY_NAME, factory);
			
		}catch(MappingException e){
			
			log.error("mapping error",e);
			
		}catch(HibernateException e){
			
			log.error("hibernate error",e);
			
		}
		
		
	}

}
